package com.shouhuyun.controller;

import com.shouhuyun.constant.MessageConstant;
import com.shouhuyun.entity.Result;
import com.shouhuyun.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.*;

@RestController
@RequestMapping("/redis")
public class RedisController {
    @Autowired
    private JedisPool jedisPool;

    /**
     *
     * @param date
     * @return
     */
    @RequestMapping("/getCheckList")
    public Result getCheckRedis(String date){
        try {
            Set<String> stringSet = jedisPool.getResource().zrevrange(date, 0, -1);
            System.out.println(stringSet);
            List<Map<String,Object>> list = new ArrayList<>();
            for (String s : stringSet) {
                Map<String,Object> map = new HashMap<>();
                //将获取到的带时间戳的字符小数转换为int类型（去掉小数）
                Double zscore = jedisPool.getResource().zscore(date, s);
                double countD = zscore.doubleValue();
                int count = (int)countD;

                map.put("name",s);
                map.put("value",count);
                list.add(map);
            }
            return new Result(true, MessageConstant.GET_REDIS_LIST_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_REDIS_LIST_FAIL);
        }
    }

    /**
     * 自定义私有方法，将不同日期的不同操作添加到redis的zset中，根据分数排序
     * @param check
     */
    public void saveRedis(String check){
        try {
            //获取当日日期
            String date = DateUtils.parseDate2String(DateUtils.getToday());
            //获取某一时刻的时间戳
            double l = System.currentTimeMillis()/1E13;

            //查询当日某一个操作的下标，如果没有则为空
            Long zrank = jedisPool.getResource().zrank(date,check);

            if (zrank != null){
                Double zscore = jedisPool.getResource().zscore(date, check);
                double countD = zscore.doubleValue();
                int count = (int)countD;
                jedisPool.getResource().zadd(date,count+1+l,check);
            } else {
                jedisPool.getResource().zadd(date,1+l,check);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
